package com.bzyd.jpa.dao;

import com.bzyd.jpa.entity.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface OrderDao extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {

    //注意findBy写法规范
    List<Order> findByUserId(Long userId);

    //根据userId过滤的分页查询
    Page<Order> findByUserId(Long userId, Pageable pageable);

    //根据订单编号查询
    Order findByOrderNo(String orderNo);


    //@Modifying表示这是写操作
    //nativeQuery = true表示用原生SQL，false表示用JPQL或者HQL
    //JPA规定写操作需要事务（或者在调用此方法的service层方法上加事务注解@Transactional）
    //类似这种写SQL的方式应尽量少用，不然会造成项目中遍地SQL，失去了JPA的初衷
    @Transactional
    @Modifying
    @Query(value = "update t_order set order_name = :orderName, update_time = now() where id = :id", nativeQuery = true)
    int updateOrderById(@Param("orderName") String orderName, @Param("id") Long id);

}
